﻿
package extremefx.i18n {
	import extremefx.DateTime;		
	/**
	 * @author Marcelo Volmaro
	 */
	internal class CCPersian {
		private static const EPOCH:int = 226895;
		
		public static function _fixedFromDMY(pDay:int, pMonth:int, pYear:int):int {
			var k:int = EPOCH - 1;

			k += 365 * (pYear - 1);
			k += (8 * pYear + 21) / 33;
			if (pMonth <= 7){
				k += 31 * (pMonth - 1);
				
			} else {
				k += 30 * (pMonth - 1) + 6;
			}
			
			return k + pDay;
		}
		
		public static function _yearFromFixed(pDate:int):int {
			return (33 * (pDate - EPOCH) + 3) / 12053 + 1;
		}
		
		public static function _dmyFromFixed(pDate:int):Array {
			var year:int = _yearFromFixed(pDate);
			var day:int = pDate - _fixedFromDMY (1, 1, year);
			var month:int;
			
			if (day < 216){
				month = day / 31 + 1;
				day = day % 31 + 1;
				
			} else {
				month = (day - 6) / 30 + 1;
				day = (day-6) % 30 + 1;
			}
			
			return [year, month, day];	
		}
		
		public static function _isLeapYear(pYear:int):Boolean {
			return (25 * pYear + 11) % 33 < 8;
		}
		
		public static function _addMonths(pTime:DateTime, pMonths:int):DateTime {
			var rd:int = CCFixed._fromDateTime(pTime);

			var a:Array = _dmyFromFixed(rd);
			var year:int = a[0];
			var month:int = a[1];
			var day:int = a[2];
			
			month += pMonths;
			var remainder:Array = [];
			year += CCMath.divMod(remainder, month, 12);
			month = int(remainder[0]);
			
			rd = _fixedFromDMY(day, month, year);
			var t:DateTime = CCFixed._toDateTime(rd);
			t.add(pTime.timeOfDay);
			return t;
		}
		
		public static function _addYears(pTime:DateTime, pYears:int):DateTime {
			var rd:int = CCFixed._fromDateTime(pTime);
			
			var a:Array = _dmyFromFixed(rd);
			var year:int = a[0];
			var month:int = a[1];
			var day:int = a[2];
			
			year += pYears;
			
			rd = _fixedFromDMY(day, month, year);
			var t:DateTime = CCFixed._toDateTime(rd);
			t.add(pTime.timeOfDay);
			return t;
		}
	}
}
